#!/bin/bash

# 创建应用文件
cat > app.py << 'EOF'
from werkzeug.wrappers import Request, Response

@Request.application
def application(request: Request) -> Response:
    return Response("Hello, World!")

if __name__ == "__main__":
    from werkzeug.serving import run_simple
    run_simple("127.0.0.1", 5000, application)
EOF

# 检查是否已安装所需依赖
if ! python3 -c "import werkzeug" 2>/dev/null; then
    echo "正在安装 werkzeug..."
    pip install werkzeug
fi

# 启动后台服务器进程
python3 app.py &
SERVER_PID=$!

# 等待服务器启动
sleep 3

# 检查服务器是否正在运行
if ! kill -0 $SERVER_PID 2>/dev/null; then
    echo "错误：服务器启动失败"
    exit 1
fi

# 测试应用响应
echo "测试应用..."
RESPONSE=$(curl -s http://127.0.0.1:5000/)
EXPECTED="Hello, World!"

if [ "$RESPONSE" = "$EXPECTED" ]; then
    echo "test scripts success"
else
    echo "✗ 测试失败：预期 '$EXPECTED'，但得到 '$RESPONSE'"
fi

# 停止服务器
kill $SERVER_PID

# 清理文件
rm -f app.py

echo "测试完成"
